package com.sentinel.demo.app.controller;

/**
 * packageName com.sentinel.demo.app.controller.TestController
 *
 * @author liudonghai
 * @version JDK 11
 * @date 2025/9/14
 * @description TODO
 */
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/hello")
    @SentinelResource(value = "hello", blockHandler = "handleException")
    public String hello() {
        return "Hello, Sentinel!";
    }

    @GetMapping("/test")
    public String test() {
        Entry entry = null;
        try {
            // 定义资源
            entry = SphU.entry("testResource");
            // 被保护的业务逻辑
            return "Test resource accessed successfully";
        } catch (Exception e) {
            // 处理被流控的逻辑
            return "Blocked by Sentinel";
        } finally {
            // 务必保证 exit，务必保证每个 entry 与 exit 配对
            if (entry != null) {
                entry.exit();
            }
        }
    }

    public String handleException(BlockException ex) {
        return "Oops, blocked by Sentinel: " + ex.getClass().getSimpleName();
    }
}
